// 目的：使用 forward_list 管理空闲节点，insert_after/erase_after O(1) 回收与分配。
#include <forward_list>
#include <array>
#include <iostream>

struct Node {
    int value;
    Node* next;
};

class ObjectPool {
public:
    ObjectPool() {
        for (auto& slot : storage_) {
            freelist_.push_front(&slot);
        }
    }

    Node* allocate(int v) {
        if (freelist_.empty()) return nullptr;
        Node* node = freelist_.front();
        freelist_.pop_front();
        node->value = v;
        node->next = nullptr;
        return node;
    }

    void deallocate(Node* node) {
        freelist_.push_front(node);
    }

    std::size_t freeCount() const {
        std::size_t count = 0;
        for (auto _ : freelist_) (void)_, ++count;
        return count;
    }

private:
    std::array<Node, 8> storage_;
    std::forward_list<Node*> freelist_;
};

int main() {
    ObjectPool pool;
    Node* a = pool.allocate(42);
    Node* b = pool.allocate(7);

    std::cout << "Allocated: " << a->value << ", " << b->value << '\n';
    std::cout << "Free slots: " << pool.freeCount() << '\n';

    pool.deallocate(a);
    pool.deallocate(b);
    std::cout << "Free slots after return: " << pool.freeCount() << '\n';
    return 0;
}